package com.boot2.core.dao.batch.insert;

import com.boot2.core.cache.redis.RedisDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author zhangweilin
 * @Description: 缓存于redis的批量提交方案
 * @date 2020/8/15
 */
@Component
public class BatchCommitDataWithRedis implements BatchCommitData {

    @Autowired(required = false)
    RedisDao redisDao;

    @Override
    public void init(String key) {

    }

    @Override
    public <T> void preCommit(String key, T t) {
        redisDao.lPush(key, t);
    }

    /**
     * 从队列取数据
     */
    @Override
    public <T> T poll(final String key) {
        return redisDao.rpop(key);
    }

    /**
     * 从队列取数据
     */
    @Override
    public <T> List<T> pollList(final String key, int size) {
        return redisDao.rpopList(key, size);
    }

    @Override
    public boolean isEmpty(final String key) {
        Long size = size(key);
        return size == 0;
    }

    @Override
    public Long size(String key) {
        Long size = redisDao.listSize(key);
        return size == null ? 0 : size;
    }

}
